#!/bin/bash

set -e

# Including common functions
. "${LB_BASE:-/usr/share/live/build}"/scripts/build.sh

# Setting static variables
DESCRIPTION="$(Echo 'including syslinux in the ISO filesystem')"
HELP=""
USAGE="${PROGRAM}"

# Reading configuration files
Read_conffiles config/all config/bootstrap config/common config/binary
Set_defaults

# Safeguards
[ "${LB_BOOTLOADER}"   = "syslinux" ] || exit 0
[ "${LB_ARCHITECTURE}" = "i386"     ] || exit 0

# Seems like we'll have work to do
Echo_message 'including syslinux in the ISO filesystem'

### Variables
LINUX_BINARY_UTILS_DIR='binary/utils/linux'
WIN32_BINARY_UTILS_DIR='binary/utils/win32'
BINARY_MBR_DIR='binary/utils/mbr'
CHROOT_SYSLINUX_BIN='chroot/usr/bin/syslinux'
CHROOT_SYSLINUX_MBR='chroot/usr/lib/SYSLINUX/gptmbr.bin'
CHROOT_TEMP_APT_SOURCES='chroot/etc/apt/sources.list.d/tmp-deb-src.list'

### Functions

syslinux_deb_version_in_chroot () {
   chroot chroot dpkg-query -W -f='${Version}\n' syslinux
}

### Main
mkdir -p "$LINUX_BINARY_UTILS_DIR" "$WIN32_BINARY_UTILS_DIR" "$BINARY_MBR_DIR"
cp "$CHROOT_SYSLINUX_BIN" "$LINUX_BINARY_UTILS_DIR/"
cp "$CHROOT_SYSLINUX_MBR" "$BINARY_MBR_DIR/mbr.bin"

cat chroot/etc/apt/sources.list chroot/etc/apt/sources.list.d/*.list \
   | grep --extended-regexp --line-regexp --invert-match \
        'deb\s+file:/root/local-packages\s+\./' \
   | grep --extended-regexp --invert-match \
        '^deb\s+http://tagged\.snapshots\.deb\.tails\.boum.org/[^/]+/torproject(/|\s)' \
   | grep --extended-regexp --invert-match \
        '^deb\s+http://time-based\.snapshots\.deb\.tails\.boum.org/torproject/' \
   | sed --regexp-extended -e 's,^deb(\s+),deb-src\1,' \
   > "$CHROOT_TEMP_APT_SOURCES"
Chroot chroot apt-get --yes update
Chroot chroot apt-get --yes install dpkg-dev
Chroot chroot apt-get source syslinux="$(syslinux_deb_version_in_chroot)"
cp chroot/syslinux-*/bios/win32/syslinux.exe "$WIN32_BINARY_UTILS_DIR/"
rm -r chroot/syslinux*
rm "$CHROOT_TEMP_APT_SOURCES"
Chroot chroot apt-get --yes purge dpkg-dev make # dpkg-dev depends on make
